#include "formsetsystem.h"
#include "ui_formsetsystem.h"
#include <QJsonObject>
#include <QJsonDocument>
FormSetSystem::FormSetSystem(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormSetSystem)
{
    ui->setupUi(this);
    this->show();
    this->setWindowTitle("系统参数设置");
    Start();
    RefTree();

}
void FormSetSystem::Start(){//初始化
    QString QX=mySQL::Permission; //读取权限
    if (QX.mid(9,1)=="0"){ //创建会计年度
        ui->cmdCreatND->setEnabled(false);
        ui->cmdDeleteND->setEnabled(false);
    }
    ui->tabWidget->setTabPosition(QTabWidget::North);//设置选项卡的方位东南西北，这次选中在西边
    ui->tabWidget->setTabText(0,"基本项目");
    ui->tabWidget->setTabText(1,"复核入账");
    ui->tabWidget->setTabText(2,"年度账套");
    ui->tabWidget->setTabText(3,"报表设置");
    //ui->tabWidget->setTabText(2,"电子发票");
    ui->tabWidget->setCurrentIndex(0);
    ui->tabWidget->setStyleSheet("QTabBar::tab { background: gray; color: white; padding: 10px; } "
                                 "QTabBar::tab:selected { background: black; } " );
    ui->cmbBBLX->clear();
    ui->cmbBBLX->addItem("科目余额表");

    QString SQL="";
    QSqlQuery query(mySQL::cn);
    SQL=QString("SELECT info FROM systeminfo where type_id='%1' and type='系统参数'").arg(mySQL::TypeId);
    QString INI="";
    QString str="";
    query.exec(SQL);
    while(query.next()){
        str=query.value("info").toString().trimmed();
    }
    //QMessageBox::warning(this,"警告",str);
    query.clear();
    //str=JCode::toXOR(str,'J'); //解密
    //QMessageBox::warning(this,"警告",str);
    if (str.left(1)=="{"){
        QJsonObject obj;
        obj=JCode::QStringTOQJson(str); //转JSON
        QString tmpstr=obj["SYDW"].toString();
        ui->txtSYDW->setText(tmpstr);
        tmpstr=obj["PZQR"].toString();
        ui->txtPZQR->setText(tmpstr);
    }
    if (ui->txtPZQR->toPlainText().trimmed()==""){
        QString tmpstr="|typeID|-|凭证年度|-|凭证月份|-|凭证类型|-|凭证编号|-|记账|-|记账日期|-|复核|-|复核日期|-|打印|-|打印日期|";
        ui->txtPZQR->setText(tmpstr);
    }
    ui->txtRZNY->setEnabled(false);
    /*
    SQL=QString("SELECT COUNT(*) AS 行数, type FROM GReport  where type_id='%1' GROUP BY type ORDER BY type").arg(mySQL::TypeId);

    query.exec(SQL);
    ui->cmbBBLX->clear();
    while(query.next()){
        ui->cmbBBLX->addItem(query.value("type").toString().trimmed());
    }*/
    RefND(); //刷新年度列表
    RefFHRZ();////刷新复核入账列表

}
void FormSetSystem::RefTree()
{
    ui->treeWidgetKM->clear();
    ui->treeWidgetKM->setHeaderLabels(QStringList() << "科目代码" << "科目名称" << "核算方式" << "核算项目" << "核算货币"<< "余额方向"  );
    ui->treeWidgetKM->header()->setSectionResizeMode(QHeaderView::ResizeToContents); //QTreeWidget设置根据内容自适应宽度
    //ui->treeWidget->setStyleSheet("QTreeWidget::item{border-right: 1px solid blue;border-left: 1px solid blue;border-bottom: 1px solid blue;}"); //加表格线
    QString SQL="";
    QString ND=mySQL::ND;
    QStringList child;
    SQL=QString("SELECT kmdm,kmmc,hsfs,xmbh,hshb,ye FROM `kmxx` WHERE type_id='%1' and nd='%2' order by kmdm").arg(mySQL::TypeId).arg(ND);
    QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
    query.exec(SQL);
    while(query.next()){
        QString str=query.value("kmdm").toString().trimmed();
         child.clear();
         child << query.value("kmdm").toString();
         child << query.value("kmmc").toString();
         child << query.value("hsfs").toString();
         child << query.value("xmbh").toString();
         child << query.value("hshb").toString();
         child << query.value("ye").toString();
         QTreeWidgetItem * citem =new QTreeWidgetItem(child);
         citem->setCheckState(0, Qt::Unchecked);
         if (str.length() ==1){
             ui->treeWidgetKM->addTopLevelItem(citem);
         }else{
             //遍历找出父节点
             bool f=false;
             QTreeWidgetItemIterator it(ui->treeWidgetKM);
                 while (*it) {
                      //(*it)->text(0);
                     if ((*it)->text(0)==str.left(str.length()-1)){
                         (*it)->addChild(citem);

                         f=true;
                     }
                     ++it;
                 }
                 if(f==false){
                     //如果减一个字符没照到上级 就减2个字符
                     QTreeWidgetItemIterator it(ui->treeWidgetKM);
                     while (*it) {
                          //(*it)->text(0);
                         if ((*it)->text(0)==str.left(str.length()-2)){
                             (*it)->addChild(citem);

                             f=true;
                         }
                         ++it;
                     }
                 }
                 if(f==false){
                     //如果减2个字符没照到上级 就减3个字符
                     QTreeWidgetItemIterator it(ui->treeWidgetKM);
                     while (*it) {
                          //(*it)->text(0);
                         if ((*it)->text(0)==str.left(str.length()-3)){
                             (*it)->addChild(citem);

                             f=true;
                         }
                         ++it;
                     }
                 }
         }
    }
    ui->treeWidgetXM->clear();
    ui->treeWidgetXM->setHeaderLabels(QStringList() << "项目代码"  << "项目名称" << "助记码" );
    ui->treeWidgetXM->header()->setSectionResizeMode(QHeaderView::ResizeToContents); //QTreeWidget设置根据内容自适应宽度
    SQL=QString("SELECT xmdm,xmmc,xmjc,xmzj FROM `hsxm` WHERE type_id='%1' and nd='%2'  order by xmdm ").arg(mySQL::TypeId).arg(ND);
    //qDebug() << SQL;
    query.exec(SQL);
    while(query.next()){
        QString str=query.value("xmdm").toString().trimmed();
        QStringList child;
         child.clear();
         child << query.value("xmdm").toString();
         child << query.value("xmmc").toString();
         child << query.value("xmzj").toString();
         QTreeWidgetItem * citem =new QTreeWidgetItem(child);
         citem->setCheckState(0, Qt::Unchecked);
         if (str.length() ==1){
             ui->treeWidgetXM->addTopLevelItem(citem);
             //ui->treeWidgetXM->expandAll();
         }else{
             //遍历找出父节点
             bool f=false;
             QTreeWidgetItemIterator it(ui->treeWidgetXM);
                 while (*it) {
                      //(*it)->text(0);
                     if ((*it)->text(0)==str.left(str.length()-1)){
                         (*it)->addChild(citem);

                         f=true;
                     }
                     ++it;
                 }
                 if(f==false){
                     //如果减一个字符没照到上级 就减2个字符
                     QTreeWidgetItemIterator it(ui->treeWidgetXM);
                     while (*it) {
                          //(*it)->text(0);
                         if ((*it)->text(0)==str.left(str.length()-2)){
                             (*it)->addChild(citem);

                             f=true;
                         }
                         ++it;
                     }
                 }
                 if(f==false){
                     //如果减2个字符没照到上级 就减3个字符
                     QTreeWidgetItemIterator it(ui->treeWidgetXM);
                     while (*it) {
                          //(*it)->text(0);
                         if ((*it)->text(0)==str.left(str.length()-3)){
                             (*it)->addChild(citem);

                             f=true;
                         }
                         ++it;
                     }
                 }
         }
    }
}
FormSetSystem::~FormSetSystem()
{
    delete ui;
}

void FormSetSystem::on_cmdTab1OK_clicked()
{
    QJsonObject obj;

    QString str=ui->txtSYDW->text();
    QString PZQR=ui->txtPZQR->toPlainText();
    mySQL::SYDW=str;
    mySQL::PZQR=PZQR;
    obj.insert("SYDW", str);
    obj.insert("PZQR", PZQR);
    QString INI="";
    INI=JCode::QJsonTOQString(obj); //转QString
    //QMessageBox::warning(this,"警告",INI);
    QString SQL="";
    QSqlQuery query(mySQL::cn);
    int idd=-1;
    SQL=QString("SELECT idd FROM systeminfo where type_id='%1' and type='系统参数'").arg(mySQL::TypeId);
    query.exec(SQL);
    while(query.next()){
        idd=query.value("idd").toInt();
    }
    query.clear();
    if (idd!=-1){
        SQL="update systeminfo set ";
        SQL+=QString("info='%1'").arg(INI);
        SQL+=QString("where idd=%1").arg(idd);
    }else{
        SQL="INSERT INTO systeminfo(type_id,type,info) VALUES (";
        SQL+=QString("'%1',").arg(mySQL::TypeId);
        SQL+=QString("'系统参数',");
        SQL+=QString("'%1')").arg(INI);
    }
    query.exec(SQL);
    //this->close();
}

void FormSetSystem::on_treeWidgetKM_itemClicked(QTreeWidgetItem *item, int column)
{
    QString str="";
    //以下4行代码只为消除警告信息
    str=item->text(0);
    int i=column;
    i++;
    str="";
    QTreeWidgetItemIterator it(ui->treeWidgetKM);
    while (*it) {
         //(*it)->text(0);
        if ((*it)->checkState(0)==Qt::Checked){
            str+=QString("%1,|").arg((*it)->text(0));
            str+=QString("%1||").arg((*it)->text(1));
            str+=QString("%1|\n").arg((*it)->text(5));
        }
        ++it;
    }
    ui->txtKMXX->setText(str);
}

void FormSetSystem::on_treeWidgetXM_itemClicked(QTreeWidgetItem *item, int column)
{
    QString str="";
    //以下4行代码只为消除警告信息
    str=item->text(0);
    int i=column;
    i++;
    str="";
    QTreeWidgetItemIterator it(ui->treeWidgetXM);
    while (*it) {
         //(*it)->text(0);
        if ((*it)->checkState(0)==Qt::Checked){
            str+=QString("%1,|").arg((*it)->text(0));
            str+=QString("%1\n").arg((*it)->text(1));
        }
        ++it;
    }
    ui->txtXMXX->setText(str);
}

void FormSetSystem::on_cmdTab2Save_clicked()
{
    QString SQL="";
    QSqlQuery query(mySQL::cn);
    SQL=QString("SELECT idd FROM GReport  where type_id='%1' and type='%2' and name='%3' ").arg(mySQL::TypeId).arg(ui->cmbBBLX->currentText()).arg(ui->cmbBBMC->currentText());
    int IDD=0;
    QString str="";
    query.exec(SQL);
    while(query.next()){
        IDD=query.value("idd").toInt();
    }
    SQL="";
    if (IDD ==0){
        SQL="INSERT INTO GReport(type_id,type,name,title,pageend,XM,kmxx) VALUES(";
        SQL+=QString("'%1',").arg(mySQL::TypeId.trimmed().replace("'","''"));
        SQL+=QString("'%1',").arg(ui->cmbBBLX->currentText().trimmed().replace("'","''"));
        SQL+=QString("'%1',").arg(ui->cmbBBMC->currentText().trimmed().replace("'","''"));
        SQL+=QString("'%1',").arg(ui->txtTitle->text().trimmed().replace("'","''"));
        SQL+=QString("'%1',").arg(ui->txtPageEnd->text().trimmed().replace("'","''"));
        SQL+=QString("'%1',").arg(ui->txtXMXX->toPlainText().trimmed().replace("'","''"));
        SQL+=QString("'%1')").arg(ui->txtKMXX->toPlainText().trimmed().replace("'","''"));
    }else{
        SQL="update GReport set ";
        SQL+=QString("type_id='%1',").arg(mySQL::TypeId.trimmed().replace("'","''"));
        SQL+=QString("type='%1',").arg(ui->cmbBBLX->currentText().trimmed().replace("'","''"));
        SQL+=QString("name='%1',").arg(ui->cmbBBMC->currentText().trimmed().replace("'","''"));
        SQL+=QString("title='%1',").arg(ui->txtTitle->text().trimmed().replace("'","''"));
        SQL+=QString("pageend='%1',").arg(ui->txtPageEnd->text().trimmed().replace("'","''"));
        SQL+=QString("XM='%1',").arg(ui->txtXMXX->toPlainText().trimmed().replace("'","''"));
        SQL+=QString("kmxx='%1'").arg(ui->txtKMXX->toPlainText().trimmed().replace("'","''"));
        SQL+=QString(" where idd=%1").arg(IDD);
    }
    if (SQL!=""){
        //QMessageBox::warning(this,"警告",SQL);
        //qDebug()<<SQL;
        query.exec(SQL);
        str="保存成功！";


        QMessageBox::warning(this,"警告",str);
    }
    str=ui->cmbBBMC->currentText().trimmed();
    SQL=QString("SELECT COUNT(*) AS 行数, name FROM GReport  where type_id='%1' and type='%2' GROUP BY name ORDER BY name").arg(mySQL::TypeId).arg(ui->cmbBBLX->currentText());
    ui->cmbBBMC->clear();
    query.exec(SQL);
    while(query.next()){
        ui->cmbBBMC->addItem(query.value("name").toString().trimmed());
    }
    //ui->txtKMXX->setText("");
    ui->cmbBBMC->setCurrentText(str);
    on_cmbBBMC_currentIndexChanged(str);
    //QMessageBox::warning(this,"警告",str);
    query.clear();
}

void FormSetSystem::on_cmbBBLX_currentTextChanged(const QString &arg1)
{
    QString SQL="";
    QSqlQuery query(mySQL::cn);
    SQL=QString("SELECT COUNT(*) AS 行数, name FROM GReport  where type_id='%1' and type='%2' GROUP BY name ORDER BY name").arg(mySQL::TypeId).arg(arg1);
    ui->cmbBBMC->clear();
    query.exec(SQL);
    while(query.next()){
        ui->cmbBBMC->addItem(query.value("name").toString().trimmed());
    }
    //QMessageBox::warning(this,"警告",str);
    query.clear();
}

void FormSetSystem::on_cmbBBMC_currentIndexChanged(const QString &arg1)
{
    QString SQL="";
    QSqlQuery query(mySQL::cn);
    SQL=QString("SELECT title,pageend,XM,kmxx FROM GReport  where type_id='%1' and type='%2' and name='%3' ").arg(mySQL::TypeId).arg(ui->cmbBBLX->currentText()).arg(arg1);

    query.exec(SQL);
    while(query.next()){
        ui->txtKMXX->setText(query.value("kmxx").toString().trimmed());
        ui->txtXMXX->setText(query.value("XM").toString().trimmed());
        ui->txtTitle->setText(query.value("title").toString().trimmed());
        ui->txtPageEnd->setText(query.value("pageend").toString().trimmed());
    }
    //QMessageBox::warning(this,"警告",str);
    query.clear();
}
void FormSetSystem::RefND() //刷新年度列表
{
    ui->treeWidgetND->clear();
    ui->treeWidgetND->setHeaderLabels(QStringList() << "年度" << "已有凭证"<< " ");
    ui->treeWidgetND->setColumnWidth(0,100);
    ui->treeWidgetND->setColumnWidth(1,100);
    ui->treeWidgetND->setColumnWidth(2,100);
    ui->treeWidgetND->header()->setDefaultAlignment(Qt::AlignCenter);

    QStringList tr1; //根节点
    QString SQL="";
    SQL=QString("SELECT nd.type_id,nd.nd,a.tot FROM nd LEFT JOIN (select type_id,nd,count(pzid) as tot from pz group by type_id,nd) as a on a.nd=nd.nd and nd.type_id=a.type_id  where nd.type_id='%1' order by  nd.nd").arg(mySQL::TypeId);
    QSqlQuery query(mySQL::cn); //查询
    query.exec(SQL);
    QString TypeID="";
    while(query.next()){
        QString str=query.value("nd").toString().trimmed();
        QString PZcount=query.value("tot").toString().trimmed();
        QStringList tr1; //根节点
        QTreeWidgetItem *tree1;//根节点
        tr1.clear();
        tr1 << str;
        tr1 <<  PZcount;
        tree1= new QTreeWidgetItem(ui->treeWidgetND, tr1);//根节点
        tree1->setTextAlignment(0,1); //左对其
        tree1->setTextAlignment(1,2);//居中
    }
    query.clear();

}

void FormSetSystem::on_cmdCreatND_clicked()
{
    QString SQL ="";
    int f=0;

    //"INSERT INTO nd(type_id,nd,bz) VALUES(11, '0000000001', '2021', '')";
    SQL=QString("select ND from nd where type_id='%1' and nd='%2'").arg(mySQL::TypeId).arg(ui->txtND->text().trimmed());
    QSqlQuery query(mySQL::cn); //查询
    query.exec(SQL);
    QString TypeID="";
    while(query.next()){
        f=1;
    }
    if(f==1){
        QString str="该账套已经存在了，无法建立！！！";
        QMessageBox::warning(this,"警告",str);
    }else{
        SQL="";
        SQL="INSERT INTO nd(type_id,nd,bz) VALUES(";
        SQL +=QString("'%1',").arg(mySQL::TypeId.replace("'","''"));
        SQL +=QString("'%1',").arg(ui->txtND->text().trimmed().replace("'","''"));
        SQL +=QString("'%1')").arg(ui->txtNDBZ->text().trimmed().replace("'","''"));
        if (SQL!=""){
            query.exec(SQL);
            QString str=QString("账套%1建立成功！！！").arg(ui->txtND->text().trimmed());
            QMessageBox::warning(this,"警告",str);
            RefND();
        }

    }
}

void FormSetSystem::on_cmdDeleteND_clicked()
{
    QString SQL ="";
    int f=0;

    //"INSERT INTO nd(type_id,nd,bz) VALUES(11, '0000000001', '2021', '')";
    SQL=QString("select count(pzid) as tot from pz where type_id='%1' and nd='%2'").arg(mySQL::TypeId).arg(ui->txtND->text().trimmed());
    QSqlQuery query(mySQL::cn); //查询
    query.exec(SQL);
    QString TypeID="";
    while(query.next()){
        f=query.value("tot").toInt();
    }
    if(f!=0){
        QString str="该账套做了凭证，无法删除！！！";
        QMessageBox::warning(this,"警告",str);
    }else{
        SQL="";
        SQL="delete from nd where ";
        SQL +=QString("type_id='%1' ").arg(mySQL::TypeId.replace("'","''"));
        SQL +=QString("and nd='%1'").arg(ui->txtND->text().trimmed().replace("'","''"));

        if (SQL!="" ){
            QString str=QString("确认删除【%1】吗？ 删除后是无法恢复的！！！！").arg(ui->txtND->text().trimmed());
            if (QMessageBox::information(NULL, "提醒", str,QMessageBox::Yes | QMessageBox::No, QMessageBox::No)==QMessageBox::Yes){
                query.exec(SQL);
                QString str=QString("账套%1删除成功！！！").arg(ui->txtND->text().trimmed());
                QMessageBox::warning(this,"警告",str);
                RefND();
            }

        }

    }
}
void FormSetSystem::RefFHRZ() //刷新复核入账信息
{
    ui->treeWidgetRZ->clear();
    ui->treeWidgetRZ->setHeaderLabels(QStringList() << "年度" << "记账年月"<< "凭证数"<<" ");
    ui->treeWidgetRZ->setColumnWidth(0,100);
    ui->treeWidgetRZ->setColumnWidth(1,100);
    ui->treeWidgetRZ->setColumnWidth(2,100);
    ui->treeWidgetRZ->header()->setDefaultAlignment(Qt::AlignCenter);

    QStringList tr1; //根节点
    QString SQL="";
    SQL=QString("SELECT nd,jzny,fh,count(pzbh) as tot FROM pzzb where type_id='%1' GROUP BY nd,jzny,fh order by  nd desc ,jzny").arg(mySQL::TypeId);
    QSqlQuery query(mySQL::cn); //查询
    query.exec(SQL);
    QString TypeID="";
    while(query.next()){
        QString ND=query.value("nd").toString().trimmed();
        QString JZNY=query.value("jzny").toString().trimmed();
        QString PZcount=query.value("tot").toString().trimmed();
        QStringList tr1; //根节点
        QTreeWidgetItem *tree1;//根节点
        tr1.clear();
        tr1 << ND;
        tr1 << JZNY;
        tr1 <<  PZcount;
        tree1= new QTreeWidgetItem(ui->treeWidgetRZ, tr1);//根节点
        tree1->setTextAlignment(0,1); //左对其
        tree1->setTextAlignment(1,1);//居中
        tree1->setTextAlignment(2,1);//居中
    }
    query.clear();

}



void FormSetSystem::on_treeWidgetRZ_itemClicked(QTreeWidgetItem *item, int column)
{
    int i=column;
    i++;
    i--;
    QString str="";
    str=item->text(1);
    ui->txtRZNY->setText(str);

}

void FormSetSystem::on_cmdRZ_clicked()
{
    QString JZNY=ui->txtRZNY->text();
    if (JZNY!=""){
        QString str="";
        str=QString("确认将所选择的记账年月[%1]全部复核入账吗？").arg(JZNY);
        if (QMessageBox::information(NULL, "提醒", str,QMessageBox::Yes | QMessageBox::No, QMessageBox::No)==QMessageBox::Yes){
            QDate currentdate = QDate::currentDate();
            QString NowDate = currentdate.toString("yyyy-MM-dd");
            QString SQL="";
            SQL="update pzzb set ";//(type_id,nd,jzny,pzbh,pzlx,jzrq,dj,jz,fhrq,fh,xgrq) VALUES (";
            SQL+=QString("fh='%1',").arg(mySQL::UserName.trimmed().replace("'","''"));
            SQL+=QString("fhrq='%1'").arg(NowDate);
            SQL+=QString(" where type_id='%1'").arg(mySQL::TypeId.trimmed().replace("'","''"));
            SQL+=QString(" and jzny='%1'").arg(JZNY);
            //QMessageBox::warning(this,"警告",SQL);
            //qDebug() << SQL;
            mySQL::cn.exec(SQL);
            QMessageBox::warning(this,"警告","复核入账成功！");
        }
    }


}

void FormSetSystem::on_cmdQXRZ_clicked()
{
    QString JZNY=ui->txtRZNY->text();
    if (JZNY!=""){
        QString str="";
        str=QString("确认将所选择的记账年月[%1]取消复核入账吗？").arg(JZNY);
        if (QMessageBox::information(NULL, "提醒", str,QMessageBox::Yes | QMessageBox::No, QMessageBox::No)==QMessageBox::Yes){
            QDate currentdate = QDate::currentDate();
            QString NowDate = currentdate.toString("yyyy-MM-dd");
            QString SQL="";
            SQL="update pzzb set ";//(type_id,nd,jzny,pzbh,pzlx,jzrq,dj,jz,fhrq,fh,xgrq) VALUES (";
            SQL+=QString("fh='%1',").arg("");
            SQL+=QString("fhrq='%1'").arg("2000-01-01");
            SQL+=QString(" where type_id='%1'").arg(mySQL::TypeId.trimmed().replace("'","''"));
            SQL+=QString(" and jzny='%1'").arg(JZNY);
            //QMessageBox::warning(this,"警告",SQL);
            //qDebug() << SQL;
            mySQL::cn.exec(SQL);
            QMessageBox::warning(this,"警告","复核入账成功！");
        }
    }
}
